import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_widget/base/base_app.dart';
import 'package:flutter_base_widget/code2/second_page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

//静态路由配置
void main() => runApp(BaseApp(homeWidget: Exam205HomePage()));

class Exam205HomePage extends StatefulWidget {
  @override
  State<Exam205HomePage> createState() => _Exam205HomePageState();
}

///代码清单 7-1-2
///lib/code7/code701_main_page.dart
class _Exam205HomePageState extends State<Exam205HomePage> {
  int _data = 0;

  @override
  Widget build(BuildContext context) {
    //Scaffold 用来搭建页面的主体结构
    return Scaffold(
      //页面的主内容区
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                _data++;

                ///第三步就是数据变化后
                ///赋值更新
                userNotifier.setAge(_data);
              },
              child: const Text("+"),
            ),
            const SizedBox(width: 40),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                BPage(),
                const SizedBox(height: 20),
                CPage(),
                const SizedBox(height: 20),
              ],
            )
          ],
        ),
      ),
    );
  }
}


///第三步 创建实例  参数为用户信息的初始信息
UserNotifier userNotifier
              = UserNotifier(UserInfo(name: "张三", age: 0));
///代码清单 7-2-3
///第四步设置监听
class BPage extends StatelessWidget {
  const BPage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      ///数据发生变化时回调
      builder: (context, UserInfo value, Widget? child) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text("B未获取到数据 ${value.age}"),
            child ?? const SizedBox(),
          ],
        );
      },
      ///监听的数据
      valueListenable: userNotifier,
      child: const Text(
        '子视图中的内容',
        style: TextStyle(color: Colors.red),
      ),
    );
  }
}

class CPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      ///数据发生变化时回调
      builder: (context, UserInfo value, child) {
        return Text("C中获取到数据 ${value.age}");
      },
      ///监听的数据
      valueListenable: userNotifier,
    );
  }
}


///第一步定义数据对象体
///代码清单 7-2-1  实际中变量可能足够的多
class UserInfo {
  String? name;
  int? age;
  UserInfo({this.name, this.age});
}

///代码清单 7-2-2
///第二步定义 数据对像 自定义 ValueNotifier
/// UserInfo 为数据类型
class UserNotifier extends ValueNotifier<UserInfo> {
  UserNotifier(UserInfo userInfo) : super(userInfo);
  //自定义更新值方法
  void setAge(int age) {
    value.age = age;
    ///通知更新
    notifyListeners();
  }
}
